#mta数据的自动更新
load 'rds_api.rb'
@rds = @rds_tt

def updatePostsMetaByMcards mcards

    print "updating #{mcards.size} mcards: "

    affected_mcards = {}

    mcards.each do |post_id, meta|
        mdoi = meta['imageCaption'].split(' ').first # MTA-PDF-1234
        usql = "update mta.posts_meta set feature_image_alt = '#{@rds.escape meta['src']}', feature_image_caption = '#{mdoi} #{@rds.escape meta['fileCaption']}' where post_id = '#{post_id}'"
        #puts usql
        #next
        res = @rds.query(usql)
        if  @rds.affected_rows == 0
            print '-'
        else
            print '.'
            affected_mcards.store post_id, meta
        end
    end

    printf " #{affected_mcards.size} updated\n"
    return affected_mcards

end

def getMobileCardsByMetaCaption mta_type
    sql = "select p.id, p.mobiledoc, m.feature_image_caption from mta.posts p left join mta.posts_meta m on (p.id = m.post_id) where p.id in (select post_id from mta.posts_meta where feature_image_caption like '%#{mta_type}%')"
    card_type = {"MTA-VIDEO"=>"video", "MTA-PDF"=>"file"}[mta_type]
    return getMobileCardsBySql sql, card_type
end

def getMobileCardsByFileExtention file_extention
    sql = "select p.id, p.mobiledoc, m.feature_image_caption from mta.posts p left join mta.posts_meta m on (p.id = m.post_id) where p.mobiledoc like '%#{file_extention}%'"
    card_types = {".mp4"=>"video", ".pdf"=>"file"}
    card_type = card_types[file_extention]
    return getMobileCardsBySql sql, card_type
end
#pdfs = getMobileCardsByFileExtention '.pdf'; pdfs.each { |key, pdf| ap pdf }
#videos = getMobileCardsByFileExtention '.mp4'; videos.each { |key, video| ap video }

def getMobileCardsBySql isql, card_type

    puts "get mobile #{card_type} cards within: #{isql}"

    affected_mcards = {}
    mcards = {}

    (queryRds(isql)).each do |q|
        post_id = q['id']

        mobiledoc_str = q['mobiledoc']
        # 检查mobiledoc是否为nil或空
        if mobiledoc_str.nil? || mobiledoc_str.empty?
            puts "警告: post_id #{post_id} 的 mobiledoc 为空，跳过处理。"
            next
        end

        begin
            mobiledoc = JSON.parse(mobiledoc_str)
        rescue JSON::ParserError => e
            puts "解析 post_id #{post_id} 的JSON时出错: #{e.message}"
            next
        end

        mobiledoc = JSON.parse q['mobiledoc']
        cards = mobiledoc['cards']
        cards.each do |card|
            card_name = card[0]
            card_data = card[1]
            if card_name && card_name == card_type && card_data['src']
                fileCaption = card_data['fileName']
                fileCaption = card_data['fileCaption'] if card_name == 'file' &&  !card_data['fileCaption'].to_s.empty?
                imageCaption = q['feature_image_caption'].to_s
                mcards.store post_id,  {"post_id"=>post_id,"src"=>card_data['src'],"fileCaption"=>fileCaption,"imageCaption"=>imageCaption,"toFix"=>(card_data['src'].length>125?true:false)}
            end
        end

    end

    return mcards

end

=begin
1）读取mta.posts中mobiledoc数据含cards和mp4的数据的记录，获得posts.id和firstVideoUrl
2）根据post_id更新meta.posts_meta中的feature_image_alt与image_caption
3) OMS将image_alt更新为文件URL，image_caption更新为[meta_type + caption]
3）这样方便selected_videos根据帖子的feature_image_alt获取mp4地址（最多支持125个字符，数据库结构已从191提高到300，但受内部限制）
4）为了确保post有posts_meta数据，且mdoi标识一致，请在封面图CAPTION中输入MTA-VIDEO-mmddnn或MTA-PDF-mmddnn等形式
=end
def updatePostsMeta
    pdfs = getMobileCardsByMetaCaption 'MTA-PDF';
    updatePostsMetaByMcards pdfs
    videos = getMobileCardsByMetaCaption 'MTA-VIDEO';
    updatePostsMetaByMcards videos
end

#updatePostsMeta
